const url = require('url');

exports.add = function (db, req, res) {
  exports.parseReceiveData(req, function (work) {
    db.query(
      'INSERT INTO work (hours, date, description) VALUES (?, ?, ?)',
      [work.get('hours'), new Date(work.get('date')), work.get('description')],
      function (err) {
        if (err) throw err;
        exports.show(db, res);
      }
    );
  });
};

exports.delete = function (db, req, res) {
  exports.parseReceiveData(req, function (work) {
    db.query('DELETE FROM work WHERE id = ?', [work.get('id')], function (err) {
      if (err) throw err;
      exports.show(db, res);
    });
  });
};

exports.archive = function (db, req, res) {
  exports.parseReceiveData(req, function (work) {
    db.query(
      'UPDATE work SET archived=1 WHERE id = ?',
      [work.get('id')],
      function (err) {
        if (err) throw err;
        exports.show(db, res);
      }
    );
  });
};

exports.show = function (db, res, showArchived) {
  const query = 'SELECT * FROM work WHERE archived = ? ORDER BY date DESC';
  const archivValue = showArchived ? 1 : 0;
  db.query(query, [archivValue], function (err, rows) {
    if (err) throw err;
    let html = showArchived ? '' : '<a href="/archived">Archived Work</a><br>';
    html += exports.workListHtml(rows);
    html += exports.workFormHtml();
    exports.sendHtml(res, html);
  });
};

exports.showArchived = function (db, res) {
  exports.show(db, res, true);
};

exports.workListHtml = function (rows) {
  let html = '<table>';
  for (const i in rows) {
    html += `
<tr>
  <td>${rows[i].date}</td>
  <td>${rows[i].hours}</td>
  <td>${rows[i].description}</td>`;
    if (!rows[i].archived) {
      html += `<td>${exports.workArchiveForm(rows[i].id)}</td>`;
    }
    html += `<td>${exports.workDeleteForm(rows[i].id)}</td>`;
  }
  html += '</tr></table>';
  return html;
};

exports.workFormHtml = function () {
  const html = `
<form method="POST" action="/">
  <p>Date (YYYY-MM-DD): <br><input name="date" type="text"></p>
  <p>Hours worked: <br><input name="hours" type="text"></p>
  <p>Description:<br><textarea name="description"></textarea></p>
  <input type="submit" value="Add">
</form>
    `;
  return html;
};

exports.workArchiveForm = function (id) {
  return exports.actionForm(id, '/archive', 'Archive');
};

exports.workDeleteForm = function (id) {
  return exports.actionForm(id, '/delete', 'Delete');
};

exports.sendHtml = function (res, html) {
  res.setHeader('Content-Type', 'text/html; charset=utf8;');
  res.setHeader('Content-Length', Buffer.byteLength(html));
  res.end(html);
};

exports.parseReceiveData = function (req, cb) {
  let body = '';
  req.setEncoding('utf8');
  req.on('data', function (chunk) {
    body += chunk;
  });
  req.on('end', function () {
    const data = new url.URLSearchParams(body);
    cb(data);
  });
};

exports.actionForm = function (id, path, label) {
  const html = `
<form method="POST" action="${path}">
  <input type="hidden" name="id" value="${id}">
  <input type="submit" value="${label}">
</form>
  `;
  return html;
};
